Godot 4 Game Development Projects - Second Edition by Chris Bradfield

Godot 4 Game Development Projects - Second Edition by Chris Bradfield

Author:Chris Bradfield
Language: eng
Format: epub
Publisher: Packt
Published: 2023-10-15T00:00:00+00:00


Adding dangerous objects

The Danger map layer is designed to hold the spike objects that will harm the player when touched. Any tile on this TileMap will cause damage to the player! Try placing a few of them where you can easily test running into them.

In the Node tab, add the Danger tilemap to a group called danger so that you can easily identify it when colliding. This will also allow you to make other harmful objects upon adding them to the same group.

About slide collisions

When a CharacterBody2D node is moved with move_and_slide(), it may collide with more than one object in the same frame’s movement. For example, when running into a corner, the body may hit the wall and the floor at the same time. You can use the get_slide_collision_count() function to find out how many collisions occurred; then, you can get information about each collision using get_slide_collision().

In the case of Player, you want to detect when a collision occurs against the Danger tilemap. You can do this just after using move_and_slide() in player.gd:

if state == HURT: return for i in get_slide_collision_count(): var collision = get_slide_collision(i) if collision.get_collider().is_in_group("danger"): hurt()

Note that before checking for a collision with the danger group, you can first check if the player is already in the HURT state. If they are, you can skip checking to see if they are colliding with a dangerous object.

The for loop iterates through the number of collisions given by get_slide_collision_count() to check each one for an object in the danger group.

Play your scene and try running into one of the spikes. You should see the player change to the HURT state (playing the animation) for a brief time before returning to IDLE. After three hits, the player will enter the DEAD state, which currently only hides the player.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.